<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    protected function setConstants() {
        
    }

    protected function _initAutoload() {
        $autoloader = new Zend_Application_Module_Autoloader(array(
                    'namespace' => 'Default_',
                    'basePath' => dirname(__FILE__),
                ));

        return $autoloader;
    }

    protected function _initSiteOptions() {


        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/' . CONFIG_FILE, APPLICATION_ENV);
        $siteConfig = $config->site; //print_r($siteParams->captcha->image->url);exit;
        Zend_Registry::set('siteConfig', $siteConfig);
    }

    protected function _initDatabase() {
        try {

            $this->bootstrap('db');
            $db = $this->getResource('db');
            $db->setFetchMode(Zend_Db::FETCH_OBJ);

            $db->query(new Zend_Db_Expr('SET NAMES utf8'));
            Zend_Db_Table_Abstract::setDefaultAdapter($db);
            Zend_Registry::set('db', $db);
        } catch (Exception $e) {
            if ($_GET['debug'] == '1') {
                echo 'DB connection error';
                echo $e->getMessage();
                //exit();
            }
            require_once(PROJECT_ROOT_DIR . '/public/problem/index.php');
            exit;
        }
    }


    protected function _initLoggers()
    {
        $logParams = $this->getOption('logs');
        //print_r($logParams);exit;

//	    $defaultWriter = new Zend_Log_Writer_Stream($logParams['directory'] . $logParams['defaultLog']);
//	    $defaultLogger = new Zend_Log($defaultWriter);

//	    $historyWriter = new Zend_Log_Writer_Stream($logParams['directory'] . $logParams['historyLog']);
//	    $historyLogger = new Zend_Log($historyWriter);


		$firebugWriter = new Zend_Log_Writer_Firebug();
		$firebugLogger = new Zend_Log($firebugWriter);

	    $translationWriter = new Zend_Log_Writer_Stream($logParams['directory'] . $logParams['untranslatedLog']);
	    $translationLogger = new Zend_Log($translationWriter);


//		$defaultLogger->setEnabled(true);
//		$historyLogger->setEnabled(true);
//		$firebugLogger->setEnabled(true);

//		$defaultLogger->log('sample message!', Zend_Log::INFO);
//	    $historyLogger->log('sample message!', Zend_Log::INFO);
//	    $firebugLogger->log('sample message!', Zend_Log::INFO);
//		$firebugLogger->warn('This is a WARNING logggg message!');

//	    Zend_Registry::set('defaultLogger', $defaultLogger);
//	    Zend_Registry::set('historyLogger', $historyLogger);
	    Zend_Registry::set('firebugLogger', $firebugLogger);
	    Zend_Registry::set('translationLogger', $translationLogger);



		//Zend_Debug::dump($config);

    }


    protected function _initViewHelpers() {
        $this->bootstrap('view');
        $view = $this->getResource('view');


        $siteConfig = Zend_Registry::get('siteConfig');

        $view->doctype('XHTML1_STRICT');
        $view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=' . $siteConfig->encoding);
        $view->headTitle()->setSeparator(' - ');


        //jquery ve translate function icin...
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $view->addHelperPath("My/View/Helper", "My_View_Helper");
        $viewRenderer->setView($view)/* ->setViewSuffix('php') */;
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

        //assign view some constants
        $view->application_client_name = CLIENT_NAME;
    }

    protected function _initActionHelpers() {
        Zend_Controller_Action_HelperBroker::addPrefix('My_Controller_Action_Helper_');
    }

    protected function _initAuth() {
        //????

        $auth = Zend_Auth::getInstance();
        Zend_Registry::set('auth', $auth);

        if ($auth->hasIdentity()) { // Identity exists; get it

            $this->view->authdata        = $auth->getIdentity(); //Zend_Debug::dump($identity);
            $this->view->isAuthenticated = true;
            Zend_Registry::set('userAuthData', $this->view->authdata);

            $sessionLoginAsUser = new Zend_Session_Namespace('LoginAsUser');
            if (!empty($sessionLoginAsUser->originalUser->user_id)) {
                $this->view->authdataOriginal = $sessionLoginAsUser->originalUser;
            }

        }
    }









    protected function _initPlugins()
   	{

   		$this->bootstrap('frontController');
   		$frontController = $this->getResource('frontController');
   		$frontController->registerPlugin(new My_Plugin_CheckBlockedIp());
        $frontController->registerPlugin(new My_Plugin_SwitchLanguage());
   		$frontController->registerPlugin(new My_Plugin_GetRequestParameters());

   	}
   	protected function _initAcl()
   	{

   		$this->bootstrap('frontController');
   		$frontController = $this->getResource('frontController');

   		$auth = Zend_Registry::get('auth');


   		if (Zend_Registry::isRegistered('Zend_Acl')) {
   			$acl = Zend_Registry::get('Zend_Acl');
   		} else {
            $acl = new Zend_Acl();
            Zend_Registry::set('Zend_Acl', $acl);
   		}
   		$frontController->registerPlugin(new My_Plugin_Acl($acl, $auth));

   	}

   	protected function _initNavigation()
   	{

           $this->bootstrap('view');
           $view = $this->getResource('view');
           if (file_exists(APPLICATION_PATH . '/configs/navigation.'.CLIENT_NAME.'.xml')) {
   			$navigationConfig = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.'.CLIENT_NAME.'.xml', 'mainmenu');
   			$navigationContainer = new Zend_Navigation($navigationConfig);

   	        $view->navigation = $navigationContainer;
   	        Zend_Registry::set('Zend_Navigation', $navigationContainer);

   		} else {
   			$view->navigation = '';
   		}


   	}

   	protected function _initDebug()
   	{
       $debugSession = new Zend_Session_Namespace(); //print_r($loginSession);
   		if (isset($_GET['debug'])) {
   			$debugSession->debug = (($_GET['debug']=='1') ? true : false);
   		}
   		define("DEBUG", $debugSession->debug);

   			if (DEBUG == true) {
   				if (!ini_get('display_startup_errors')) {
   				    ini_set('display_startup_errors', 1);
   				}
   				if (!ini_get('display_errors')) {
   				    ini_set('display_errors', 1);
   				}

   				// turn on profiler:
   				$db = Zend_Registry::get('db');
   				$db->getProfiler()->setEnabled(true);

   				$firebugLogger = Zend_Registry::get('firebugLogger');
   				$firebugLogger->warn('DEBUG MODE IS ON!');

   				$this->view->headTitle('['.APPLICATION_ENV.':'. php_uname('n') .']', 'PREPEND');
   			}

   	}


       protected function _initLanguage()
      	{
           $siteConfig     = Zend_Registry::get('siteConfig');
           $defaultLang    = $siteConfig->language->default;
           $availableLangs = $siteConfig->language->enabledLanguages->toArray();

           $langSession = new Zend_Session_Namespace(); //print_r($loginSession);

           if (empty($langSession->language)) {
               $langSession->language = $defaultLang;
               $langSession->locale   = $availableLangs[$defaultLang];
           }

           if (array_key_exists($langSession->language, $availableLangs)) {
               $langSession->language = $langSession->language;
               $langSession->locale   = $availableLangs[$langSession->language];
           }

       }

       protected function _initRoutes()
      	{
      		$this->bootstrap('frontController');
      		$frontController = $this->getResource('frontController');
      		$router = $frontController->getRouter();// Get Router

           //DEFAULT ROUTE
           $routeDefault = new Zend_Controller_Router_Route_Module(
               array(),
               $frontController->getDispatcher(),
               $frontController->getRequest()
           );

           $langSession = new Zend_Session_Namespace(); //print_r($loginSession);
           //LANGUAGE PREFIX ROUTE
           $routeLang = new Zend_Controller_Router_Route(
              ':language',
              array('language' => $langSession->language),
              array('language' => '[a-z]{2}')
           );

           $routeLangDefault = $routeLang->chain($routeDefault);

           $router->addRoute('routeLang', $routeLang);
           $router->addRoute('default', $routeLangDefault);

      	}


       protected function _initTranslation()
       {
           $siteConfig = Zend_Registry::get('siteConfig');

           /* ** ** ** ** ** ** ** ** ** ** ** ** ** * */
           /* ** ** ** ** ** ** ** ** ** ** ** ** ** * */
           $frontendOptions = array('automatic_serialization' => true);
           $backendOptions  = array('cache_dir' => $siteConfig->cache->path.'/cln');
           $cache = Zend_Cache::factory('Core',
                                        'File',
                                        $frontendOptions,
                                        $backendOptions);
           Zend_Translate::setCache($cache);
           /* ** ** ** ** ** ** ** ** ** ** ** ** ** * */
           /* ** ** ** ** ** ** ** ** ** ** ** ** ** * */

           $langSession = new Zend_Session_Namespace(); //print_r($loginSession);

           $disableUntranslatedNotices = (APPLICATION_ENV == 'development') ? false : true;
           $logUntranslated            = (APPLICATION_ENV == 'development') ? true : false;
           $translationLogger          = Zend_Registry::get('translationLogger');
           $translateOptions           = array('scan' => 'directory', 'disableNotices' => $disableUntranslatedNotices, 'logUntranslated' => $logUntranslated, 'log' => $translationLogger, 'logMessage' => "%locale%: AA '%message%' => '%message%',",);

           $translateObj = new Zend_Translate(
               array(
                   'adapter'         => 'gettext',
                   'content'         => APPLICATION_PATH . '/languages/' . $langSession->locale . '/' . $langSession->locale . '.mo',
                   'locale'          => $langSession->locale,

                   'scan'            => Zend_Translate::LOCALE_FILENAME,
                   'disableNotices'  => $disableUntranslatedNotices,
                   'logUntranslated' => $logUntranslated,
                   'log'             => $translationLogger,
                   'logMessage'      => "%locale%: GETTEXT '%message%' => '%message%',",
               )
           );
           ;

           Zend_Registry::set('Zend_Translate', $translateObj);
           Zend_Form::setDefaultTranslator($translateObj);


       }

   	protected function _initModules()
   	{
   //		$this->bootstrap('frontController');
   //		$frontController = $this->getResource('frontController');
   //		$frontController->addModuleDirectory(APPLICATION_PATH . '/modules');

   	}

   	protected function _initZFDebug()
   	{

   		if (DEBUG == true) {
   			if (APPLICATION_ENV == 'development') {
   			    $autoloader = Zend_Loader_Autoloader::getInstance();
   			    $autoloader->registerNamespace('ZFDebug');

   			    $options = array(
   			        'plugins' => array('Variables',
   			                           'File' => array('base_path' => PROJECT_ROOT_DIR),
   			                           'Memory',
   			                           'Time',
   			                           'Registry',
   			                           'Exception')
   			    );

   			    $zfdebug = new ZFDebug_Controller_Plugin_Debug($options);

   			    $this->bootstrap('frontController');
   			    $frontController = $this->getResource('frontController');
   			    $frontController->registerPlugin($zfdebug);
   			}
   		}


   	}

    protected function _initCache() {


    /*
         try {


            $this->bootstrap('cachemanager');
            $cacheManager = $this->getResource('cachemanager');

            $databaseCache = $cacheManager->getCache('database');
            if (!$databaseCache) {
                throw new Exception('Init Cache Error (DB Cache Config Error)!');
            }
            Zend_Db_Table_Abstract::setDefaultMetadataCache($databaseCache);


        } catch (Exception $e) {
            require_once(PROJECT_ROOT_DIR . '/public/problem/index.php');
            exit;
        }
    */
    }



}
